package com.lazyJr.test.sort;

/**
 * Created by liuyangfx on 16-3-14.
 */
public class BubbleSort {
    //一般版
    public void sort(int [] a) {
        for(int i=0;i<a.length-1;i++){
            for(int j=0;j<a.length-1;j++){
                if(less(a[j+1],a[j])){
                    exch(a,j,j+1);
                }
            }
        }
    }

    //高效版
    public void sort１(int[] a) {
        for(int i=0;i<a.length-1;i++){
            boolean didSwap = false;
            for(int j=0;j<a.length-1;j++){
                if(less(a[j+1],a[j])){
                    exch(a,j,j+1);
                    didSwap = true;
                }
            }
            if(!didSwap) return ;
        }
    }


    private boolean less(int v,int w){
        return (v - w) < 0;
    }

    private void exch(int[] a,int i,int j){
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    public static void main(String[] args) {
//        int [] a={1,2,5,5,2,7,9,10,20,13};
        int [] a = {1,2,3,4,5,6,7,8};
        BubbleSort bs = new BubbleSort();
        bs.sort(a);
        for(int i = 0;i < a.length;i++) {
            System.out.println(a[i]);
        }
    }
}
